import {
  Button,
  Form,
  Input,
  InputNumber,
  Steps,
  Table,
  Pagination,
  Tooltip,
  Descriptions,
  message,
} from "antd";
import Layout from "../Shared/Layout";
import { request } from "../../Api/api";
import React, { useEffect, useRef, useState, useCallback } from "react";
import { getTypeName, getDiffcultLevelName } from "../../Api/name";
import Timer from "../../Components/Timer";
import CardList from "../../Components/CardList";
import Cookie from "../../Api/cookie";

const TestPaperAdd = () => {
  const [questionList, setQuestionList] = useState([]);
  const [page, setPage] = useState({ current: 1, pageSize: 4 });
  const [where, setWhere] = useState({ searchWord: "" });
  const [total, setTotal] = useState(0);
  const bind = useCallback(async () => {
    const res = await request(
      "/question/pagination",
      { page: page.current, limit: page.pageSize, key: where.searchWord },
      "GET"
    );
    if (res.code >= 0) {
      setQuestionList(res.data.data);
      setTotal(res.data.total);
    }
  }, [page, where]);
  useEffect(() => {
    async function fetchData() {
      await bind();
    }
    fetchData();
  }, [bind]);
  // 监听index变化，更新form
  const [index, setIndex] = useState(0);
  useEffect(() => {
    try {
      // 页面加载时，从缓存中获取tags
      const t = JSON.parse(localStorage.getItem("tags"));
      if (t) {
        setTags(t);
        testInfoForm.current?.setFieldsValue({
          name: t[0].name,
          explain: t[0].explain,
          hours: t[0].hours,
          minutes: t[0].minutes,
          point: t[0].point,
          passPoint: t[0].passPoint,
        });
      }
      // 获取index
      const i = localStorage.getItem("index");
      if (i) {
        setIndex(parseInt(i));
      }
    } catch (error) {
      console.log(error);
    }
  }, [index]);
  const testInfoForm = useRef(null);
  const submitBotton1 = useRef(null);
  const submitBotton2 = useRef(null);
  const submitBotton3 = useRef(null);
  // 添加试卷流程记录的数据
  const [tags, setTags] = useState([
    {
      title: "试卷信息",
      status: "process",
      time: "",
      name: "",
      explain: "",
      hours: null,
      minutes: null,
      point: null,
      passPoint: null,
    },
    {
      title: "添加题目",
      status: "wait",
      time: "",
      questions: [],
    },
    {
      title: "提交试卷",
      status: "wait",
      time: "",
      questions: [],
    },
  ]);
  const columns = [
    {
      title: (
        <>
          <div
            style={{
              display: "flex",
              width: "100%",
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
              }}
            >
              题目&nbsp;&nbsp;
            </div>
            <div style={{ width: "300px" }}>
              <Input.Search
                placeholder="搜索题目"
                value={where.searchWord}
                onChange={(e) => {
                  setWhere({ searchWord: e.target.value });
                }}
              />
            </div>
          </div>
        </>
      ),
      dataIndex: "content",
      key: "content",
      width: 400,
      ellipsis: true,
      render: (_, { content }) => (
        <>
          <Tooltip title={content} placement="topLeft">
            <span title={""}>{content}</span>
          </Tooltip>
        </>
      ),
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      render: (_, { type }) => getTypeName(type),
      width: 100,
      ellipsis: true,
    },
    {
      title: "难度",
      dataIndex: "diffcultLevel",
      key: "diffcultLevel",
      render: (_, { diffcultLevel }) => getDiffcultLevelName(diffcultLevel),
      width: 100,
      ellipsis: true,
    },
  ];
  // 当索引改变时，改变标签状态
  const changeStatus = (newIndex) => {
    localStorageSetIndex(newIndex);
    const temp = tags.map((d, i) => {
      if (i === newIndex && d.status === "wait") {
        d.status = "process";
      } else if (d.status === "process") {
        d.status = "wait";
      }
      return d;
    });
    localStorageSetTags(temp);
  };
  // 设置tags同时存入缓存
  const localStorageSetTags = (tags) => {
    setTags(tags);
    localStorage.setItem("tags", JSON.stringify(tags));
  };
  // 设置Index同时存入缓存
  const localStorageSetIndex = (index) => {
    setIndex(index);
    localStorage.setItem("index", index);
  };
  // 触发对应表单提交
  const checkRules = () => {
    switch (index) {
      case 0:
        submitBotton1.current.click();
        break;
      case 1:
        submitBotton2.current.click();
        break;
      case 2:
        submitBotton3.current.click();
        break;
      default:
        break;
    }
    //如果验证成功，则更新状态
  };
  // 点击上一步
  const prevStep = () => {
    if (index > 0) {
      changeStatus(index - 1);
    }
  };
  // 点击下一步
  const nextStep = () => {
    if (index < tags.length - 1) {
      checkRules();
    }
  };
  // 步骤条数据
  const items = [
    {
      title: "试卷信息",
      subTitle: (
        <Timer
          name={"timer1"}
          isRuning={index === 0 && tags[0].status === "process"}
        />
      ),
      status: tags[0].status,
      description: "需要设定试卷的属性",
    },
    {
      title: "添加题目",
      subTitle: (
        <Timer
          name={"timer2"}
          isRuning={index === 1 && tags[1].status === "process"}
        />
      ),
      status: tags[1].status,
      description: "需要添加题目到试卷中",
    },
    {
      title: "提交试卷",
      subTitle: (
        <Timer
          name={"timer3"}
          isRuning={index === 2 && tags[2].status === "process"}
        />
      ),
      status: tags[2].status,
      description: "需要检查试卷并提交",
    },
  ];
  return (
    <Layout>
      <div style={{ height: "94px" }}>
        <Steps
          type="navigation"
          size="small"
          current={index}
          className="site-navigation-steps"
          items={items}
        />
      </div>
      <div
        style={{
          height: "calc(100% - 94px)",
          overflow: "auto",
        }}
      >
        <div>
          {(() => {
            switch (index) {
              case 0:
                return (
                  <Form
                    style={{ marginTop: "20px" }}
                    ref={testInfoForm}
                    name="testInfo"
                    scrollToFirstError={true}
                    layout="horizontal"
                    labelCol={{
                      span: 3,
                    }}
                    wrapperCol={{
                      span: 16,
                    }}
                    onFinish={() => {
                      changeStatus(index + 1);
                      const temp = tags.map((d, i) => {
                        if (i === index) {
                          d.status = "finish";
                        }
                        return d;
                      });
                      localStorageSetTags(temp);
                    }}
                    onFinishFailed={() => {
                      const temp = tags.map((d, i) => {
                        if (i === index) {
                          d.status = "process";
                        }
                        return d;
                      });
                      localStorageSetTags(temp);
                    }}
                    initialValues={{
                      name: "",
                      explain: "",
                      hours: null,
                      minutes: null,
                      point: null,
                      passPoint: null,
                    }}
                  >
                    <Form.Item
                      label="试卷名称"
                      name="name"
                      rules={[{ required: true, message: "请输入试卷名称" }]}
                    >
                      <Input
                        placeholder="请输入"
                        value={tags[0].name}
                        onChange={(e) => {
                          localStorageSetTags(
                            tags.map((d, i) => {
                              if (i === 0) {
                                d.name = e.target.value;
                              }
                              return d;
                            })
                          );
                        }}
                      />
                    </Form.Item>
                    <Form.Item
                      label="试卷描述"
                      name="explain"
                      rules={[{ required: true, message: "请输入试卷描述" }]}
                    >
                      <Input.TextArea
                        placeholder="请输入"
                        onChange={(e) => {
                          localStorageSetTags(
                            tags.map((d, i) => {
                              if (i === 0) {
                                d.explain = e.target.value;
                              }
                              return d;
                            })
                          );
                        }}
                      />
                    </Form.Item>
                    <Form.Item
                      label="试卷时长"
                      name={"howLong"}
                      required
                      rules={[
                        {
                          validator: () => {
                            if (tags[0].hours * 60 + tags[0].minutes < 10) {
                              return Promise.reject("时长不能小于10分钟");
                            }
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputNumber
                        min={0}
                        max={7200}
                        value={tags[0].hours}
                        onChange={(v) => {
                          localStorageSetTags(
                            tags.map((d, i) => {
                              if (i === 0) {
                                d.hours = v;
                              }
                              return d;
                            })
                          );
                        }}
                      />
                      小时
                      <InputNumber
                        min={0}
                        max={59}
                        value={tags[0].minutes}
                        onChange={(v) => {
                          localStorageSetTags(
                            tags.map((d, i) => {
                              if (i === 0) {
                                d.minutes = v;
                              }
                              return d;
                            })
                          );
                        }}
                      />
                      分钟
                    </Form.Item>
                    <Form.Item
                      label="试卷分值"
                      name={"point"}
                      rules={[{ required: true, message: "请输入试卷分值" }]}
                    >
                      <InputNumber
                        min={1}
                        max={100000}
                        onChange={(v) => {
                          localStorageSetTags(
                            tags.map((d, i) => {
                              if (i === 0) {
                                d.point = v;
                              }
                              return d;
                            })
                          );
                        }}
                      />
                    </Form.Item>
                    <Form.Item
                      label="及格分值"
                      name={"passPoint"}
                      rules={[{ required: true, message: "请输入及格分值" }]}
                    >
                      <InputNumber
                        min={1}
                        max={tags[0].point}
                        onChange={(v) => {
                          localStorageSetTags(
                            tags.map((d, i) => {
                              if (i === 0) {
                                d.passPoint = v;
                              }
                              return d;
                            })
                          );
                        }}
                      />
                    </Form.Item>
                    <button
                      ref={submitBotton1}
                      type="submit"
                      style={{ display: "none" }}
                    ></button>
                  </Form>
                );
              case 1:
                return (
                  <div className="table-container">
                    <div style={{ display: "flex" }}>
                      <div style={{ width: "800px" }}>
                        <Table
                          rowSelection={{
                            fixed: true,
                            selectedRowKeys: tags[1].questions.map((d) => d.id),
                            onChange: (selectedRowKeys, selectedRows) => {
                              const questionListIds = questionList.map(
                                (d) => d.id
                              );
                              // 排除在当前数据列表中未选中的
                              const deletedQuestions = tags[1].questions.filter(
                                (d) =>
                                  !(
                                    questionListIds.includes(d.id) &&
                                    !selectedRowKeys.includes(d.id)
                                  )
                              );
                              // 选中的且不在问题列表中
                              const needAddQuestions = selectedRows
                                .filter(
                                  (d) =>
                                    !tags[1].questions
                                      .map((d) => d.id)
                                      .includes(d.id)
                                )
                                .map((d) => {
                                  return {
                                    id: d.id,
                                    question: d.content,
                                    answer: d.answer,
                                    type: d.type,
                                  };
                                });
                              const newQuestions =
                                deletedQuestions.concat(needAddQuestions);
                              const temp = tags.map((d, i) => {
                                if (i === 1) {
                                  d.questions = newQuestions;
                                }
                                return d;
                              });
                              localStorageSetTags(temp);
                            },
                          }}
                          bordered={true}
                          sticky={true}
                          pagination={false}
                          rowKey={(record) => record.id}
                          dataSource={questionList}
                          columns={columns}
                        />
                        <Pagination
                          total={total}
                          current={page.current}
                          pageSize={page.pageSize}
                          onChange={(current, pageSize) =>
                            setPage({ current, pageSize })
                          }
                          showQuickJumper={true}
                        />
                      </div>
                      <div style={{ width: "calc(100% - 800px)" }}>
                        <Form
                          name="addQuestion"
                          scrollToFirstError={true}
                          layout="horizontal"
                          labelCol={{
                            span: 0,
                          }}
                          wrapperCol={{
                            span: 24,
                          }}
                          onFinish={() => {
                            changeStatus(index + 1);
                          }}
                          onFinishFailed={() => {
                            const temp = tags.map((d, i) => {
                              if (i === index) {
                                d.status = "process";
                              }
                              return d;
                            });
                            localStorageSetTags(temp);
                          }}
                        >
                          <Form.Item
                            name="questions"
                            rules={[
                              {
                                validator: () => {
                                  if (tags[1].questions.length === 0) {
                                    return Promise.reject("请至少选择一个题目");
                                  }
                                  var sumPoint = 0;
                                  tags[1].questions.forEach((d) => {
                                    sumPoint += isNaN(d.point) ? 0 : d.point;
                                  });
                                  if (sumPoint !== tags[0].point) {
                                    return Promise.reject(
                                      "题目总分与设定分数(" +
                                        tags[0].point +
                                        ")不相等"
                                    );
                                  }
                                  const i = tags[1].questions.findIndex(
                                    (d) => isNaN(d.point) || d.point === 0
                                  );
                                  if (i !== -1) {
                                    return Promise.reject(
                                      "题目(" + (i + 1) + ")分值不能为0"
                                    );
                                  }
                                  return Promise.resolve();
                                },
                              },
                            ]}
                          >
                            <div style={{ height: "300px" }}>
                              <CardList
                                cards={tags[1].questions}
                                onPointChange={({ id, point }) => {
                                  const temp = tags.map((d, i) => {
                                    if (i === 1) {
                                      d.questions = d.questions.map((e) => {
                                        if (e.id === id) {
                                          e.point = point;
                                        }
                                        return e;
                                      });
                                    }
                                    return d;
                                  });
                                  localStorageSetTags(temp);
                                }}
                              ></CardList>
                            </div>
                          </Form.Item>
                          <button
                            ref={submitBotton2}
                            type="submit"
                            style={{ display: "none" }}
                          ></button>
                        </Form>
                      </div>
                    </div>
                  </div>
                );
              case 2:
                return (
                  <>
                    <Descriptions
                      bordered={true}
                      gutter={24}
                      style={{ marginTop: "20px" }}
                    >
                      <Descriptions.Item label="试卷名称">
                        {tags[0].name}
                      </Descriptions.Item>
                      <Descriptions.Item label="试卷描述">
                        {tags[0].explain}
                      </Descriptions.Item>
                      <Descriptions.Item label="试卷时长">
                        {tags[0].hours} 小时 {tags[0].minutes} 分钟
                      </Descriptions.Item>
                      <Descriptions.Item label="试卷分值">
                        {tags[0].point}
                      </Descriptions.Item>
                      <Descriptions.Item label="及格分值">
                        {tags[0].passPoint}
                      </Descriptions.Item>
                    </Descriptions>
                    <Table
                      bordered={true}
                      rowKey={({ id }) => id}
                      dataSource={tags[1].questions}
                      pagination={false}
                    >
                      <Table.Column
                        title="题目"
                        width={400}
                        ellipsis={true}
                        dataIndex="question"
                        render={(_, { question }) => {
                          return (
                            <Tooltip title={question} placement="topLeft">
                              <span title="">{question}</span>
                            </Tooltip>
                          );
                        }}
                      />
                      <Table.Column
                        title="答案"
                        width={200}
                        ellipsis={true}
                        dataIndex="answer"
                        render={(_, { answer }) => {
                          return (
                            <Tooltip
                              title={answer.split("\n").map((d, i) => {
                                return <p key={i}>{d}</p>;
                              })}
                              placement="topLeft"
                            >
                              <span title="">{answer}</span>
                            </Tooltip>
                          );
                        }}
                      />
                      <Table.Column
                        title="类型"
                        width={100}
                        ellipsis={true}
                        dataIndex={"type"}
                        render={(_, { type }) => {
                          return getTypeName(type);
                        }}
                      />
                      <Table.Column
                        title="分值"
                        width={100}
                        ellipsis={true}
                        dataIndex="point"
                      />
                    </Table>
                    <Form
                      onFinish={async () => {
                        // 整合数据提交
                        const data = {
                          name: tags[0].name,
                          explain: tags[0].explain,
                          examTime:
                            (tags[0].hours ?? 0) + ":" + (tags[0].minutes ?? 0),
                          sumPoint: tags[0].point,
                          passPoint: tags[0].passPoint,
                          uid: Cookie.get("uid"),
                          testPaperDetails: tags[1].questions.map((d, i) => {
                            return {
                              questionId: d.id,
                              point: d.point,
                              no: i + 1,
                            };
                          }),
                        };
                        const res = await request(
                          "/testPaper/add",
                          data,
                          "POST"
                        );
                        if (res.code >= 0) {
                          message.success(res.message);
                          // 提交成功的状态处理
                          var temp = tags.map((d, i) => {
                            if (i === 2) {
                              d.status = "finish";
                            }
                            return d;
                          });
                          localStorageSetTags(temp);
                          localStorage.removeItem("tags");
                          localStorage.removeItem("index");
                          localStorage.removeItem("timer1");
                          localStorage.removeItem("timer2");
                          localStorage.removeItem("timer3");
                        } else {
                          message.error(res.message);
                        }
                      }}
                    >
                      <Form.Item
                        name="checkTime"
                        rules={[
                          {
                            validator: () => {
                              const [hour, minute, second] = localStorage
                                .getItem("timer3")
                                .split(":")
                                .map(Number);
                              if (hour === 0 && minute === 0 && second < 20) {
                                return Promise.reject(
                                  "检查时间还剩" + (20 - second) + "秒"
                                );
                              }
                              return Promise.resolve();
                            },
                          },
                        ]}
                      >
                        <div></div>
                      </Form.Item>
                      <button
                        ref={submitBotton3}
                        type="submit"
                        style={{ display: "none" }}
                      ></button>
                    </Form>
                  </>
                );
              default:
                return null;
            }
          })()}
        </div>
        {tags[2].status === "finish" ? null : (
          <div
            style={{
              height: "40px",
              justifyContent: "flex-end", // 将内容推到右边
              width: "calc(100% - 20px)", // 确保 div 占满宽度
              display: "flex",
              padding: "0 20px 0 0",
            }}
          >
            {index > 0 ? (
              <Button type="primary" className="extra-btn" onClick={prevStep}>
                上一步
              </Button>
            ) : null}
            {index < tags.length - 1 ? (
              <Button type="primary" className="extra-btn" onClick={nextStep}>
                下一步
              </Button>
            ) : (
              <Button
                type="primary"
                className="extra-btn"
                onClick={() => {
                  checkRules();
                }}
              >
                提交
              </Button>
            )}
          </div>
        )}
      </div>
    </Layout>
  );
};
export default TestPaperAdd;
